package com.liu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.common.BaseContext;
import com.liu.common.R;
import com.liu.entity.Orders;
import com.liu.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 订单
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {

    @Resource
    private OrdersService ordersService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){

        ordersService.submit(orders);

        return R.success("订单提交成功");
    }


    /**
     * 后台订单明细分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime){
        // 构造分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        // 构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        // 添加过滤条件
        queryWrapper.like(number != null,Orders::getNumber, number);
        queryWrapper.between(beginTime != null && endTime != null, Orders::getOrderTime, beginTime, endTime);

        // 添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        // 执行查询
        ordersService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }


    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize){

        // 获取当前登录用户的id
        Long currentId = BaseContext.getCurrentId();
        // 构造分页构造器
        Page<Orders> orderPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, currentId);
        queryWrapper.orderByDesc(Orders::getOrderTime);

        ordersService.page(orderPage, queryWrapper);
        return R.success(orderPage);
    }
}
